//
//  WSTimer.m
//  007---Dispatch_source
//
//  Created by zhangcong on 2019/3/14.
//  Copyright © 2019 zhangcong. All rights reserved.
//

#import "WSTimer.h"

@interface WSTimer ()

@property (strong,nonatomic) dispatch_source_t timer;
@property (copy,nonatomic) TimerBlock timeBlock;


@end

@implementation WSTimer

- (instancetype)initWithTimeInterval:(NSTimeInterval)interval autoStart:(BOOL)autoStart repeats:(BOOL)repeats
{
    self = [super init];
    if (self) {
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
        
        //设置启动时间
        uint64_t jiange = (uint64_t)(interval * NSEC_PER_SEC);     //间隔
        dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, jiange);
        dispatch_source_set_timer(self.timer, start, jiange, 0);
        
        //设置回调
        dispatch_source_set_event_handler(self.timer, ^{
            if (self.timeBlock) {
                self.timeBlock(self);
            }
            if (!repeats) {
                [self stop];
            }
        });
        
        if (autoStart)
            [self start];
        
    }
    return self;
}

- (void)start {
    if (self.timer) {
        dispatch_resume(self.timer);
    }
}

- (void)suspend {
    if (self.timer) {
        dispatch_suspend(self.timer);
    }
}

- (void)stop {
    if (self.timer) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
}

+ (WSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(TimerBlock)block {
    WSTimer * timer = [[WSTimer alloc] initWithTimeInterval:interval autoStart:YES repeats:repeats];
    timer.timeBlock = block;
    return timer;
}

+ (WSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(TimerBlock)block {
    WSTimer * timer = [[WSTimer alloc] initWithTimeInterval:interval autoStart:NO repeats:repeats];
    timer.timeBlock = block;
    return timer;
}

@end
